// import { inExpression, likeExpression } from '@/utils/definitionExpressionHelper.js';
// import { Button, Select, InputNumber, Space, Checkbox } from 'antd';
// import { viewUtils } from '@/utils/arcgis';
import styles from './index.less';
import React, { useEffect, useState, useRef } from 'react';
import { useSelector, useDispatch, connect } from 'umi';
import kls from 'classnames';
import { WORKING_TAB } from '@/models/app';
import { Tabs } from 'antd';
import { CloseOutlined, PhoneOutlined, EnvironmentOutlined } from '@ant-design/icons';
import layerUtils from '@/utils/arcgis/layer/index';
import { jsapi, viewUtils } from '@/utils/arcgis';
import { getSingleWbsStatus } from '@/services/bimServices';

// wbs质量验收 又称 工序验收
// wbs质量问题
// wbs安全问题
import {
  getQualityProcessAccept,
  getQualityInspect,
  getSafetyInspect,
  // getDangerSourceExamine,
} from '@/services/bimServices.js';

const TAB_CFG = [
  {
    tab: 'wbs详情',
    key: '1',
  },
  {
    tab: '验收进度',
    key: '2',
  },
  {
    tab: '质量问题',
    key: '3',
  },
  {
    tab: '安全问题',
    key: '4',
  },
];

const { TabPane } = Tabs;

const TEXT_PLACE_HOLDER = '暂无数据';

function BlockInfo() {
  const dispatch = useDispatch();
  const selectedWbs = useSelector(s => s.projectPage.selectedWbs);
  const selectedId = useSelector(s => s.projectPage.selectedId);
  const curProjId = useSelector(s => s.app.curProjId);
  const [curWorkingTab, setCurWorkingTab] = useState('1');
  const [isVisible, setIsVisible] = useState<any>(true);
  const [processAccept, setProcessAccept] = useState<any>(null);
  const [qualityInspect, setQualityInspect] = useState<any>(null);
  const [safetyInspect, setSafetyInspect] = useState<any>(null);
  const [wbsData, setWbsData] = useState<any>(null);
  let wbsCode = window.localStorage.getItem('wbsCode') || '';
  const searchStr = `?wbsCode=${selectedWbs}&projectId=${curProjId}`;

  useEffect(() => {
    handleIdChange(selectedWbs, selectedId);
    const fetchDataAsync = async () => {
      const result = await getSingleWbsStatus(wbsCode);
      setWbsData(result);
    };
    fetchDataAsync();
  }, [selectedWbs, selectedId]);

  async function handleIdChange(selectedWbs, selectedId) {
    if (!selectedWbs) {
      setProcessAccept(null);
    }
    if (!selectedId) {
      setIsVisible(false);
      setQualityInspect(null);
      setSafetyInspect(null);
    }
    if (!selectedWbs && !selectedId) {
      return;
    }
    let workingTab = { cur: '1' };
    if (selectedWbs) {
      await Promise.all([getQualityProcessAccept(selectedWbs)]).then(([_processAccept]) => {
        setProcessAccept(_processAccept);
      });
    }

    if (selectedId) {
      try {
        await getQualityInspect(selectedId).then(_qualityInspect => {
          if (_qualityInspect.linkUrl) {
            setQualityInspect(_qualityInspect);
            workingTab.cur = '2';
          } else {
            setQualityInspect(null);
          }
        });

        await getSafetyInspect(selectedId).then(_safetyInspect => {
          if (_safetyInspect.linkUrl) {
            setSafetyInspect(_safetyInspect);
            workingTab.cur = '3';
          } else {
            setSafetyInspect(null);
          }
        });
      } catch (error) {
        console.error(error);
      }
    }
    setCurWorkingTab(workingTab.cur);
    setIsVisible(true);
  }

  function handleCloseClick() {
    setIsVisible(false);
    dispatch({
      type: 'projectPage/updateState',
      payload: {
        selectedWbs: '',
        selectedId: '',
      },
    });
    if (window.highlightSelect) {
      window.highlightSelect.remove();
    }
  }

  const renderBar = (activeNum, totalNum) => {
    if (!activeNum || !totalNum) {
      return '';
    }
    activeNum = +activeNum;
    totalNum = +totalNum;
    // console.log(activeNum, totalNum);
    return (
      <div className={styles.bar}>
        {[...Array(totalNum)].map((_, i) => {
          return (
            <div
              key={i}
              style={{ width: `${100 / totalNum - 2}%` }}
              className={kls(styles.barItem, {
                [styles.barItemActive]: i < activeNum,
              })}
            ></div>
          );
        })}
      </div>
    );
  };

  async function toggleLayerVisible(title) {
    const view = await viewUtils.isViewReady();
    const layer = layerUtils.getLayerByTitle(view, title);
    if (layer) {
      layer.visible = !layer.visible;
    }
  }
  function renderPoiPopup(attributes = {}) {
    let params = new URL(document.location).searchParams;
    let projectId = params.get('i');
    // let wbsCode = attributes['WBS编码'];
    if (!wbsCode) {
      return (
        <div className="c-popup">
          <p className="c-popup-p">没有wbs编码</p>
        </div>
      );
    }
    let data = { wbsName: '', taskStatusDesc: '', calculateStatusDesc: '', linkUrl: '' };
    if (wbsData) data = wbsData;
    return (
      <div className="c-popup">
        <p className="c-popup-p">
          {data.wbsName}
          <span className="c-popup-status">{data.taskStatusDesc}</span>
        </p>
        <p className="c-popup-p">
          wbsCode <span>{wbsCode || ''} </span>
        </p>
        <div className="c-popup-footer">
          <div className="c-popup-address">{data.calculateStatusDesc}</div>
          <a
            className="c-popup-link"
            target="_blank"
            href={data.linkUrl + '?wbsCode=' + wbsCode + '&projectId=' + projectId}
          >
            查看
          </a>
        </div>
      </div>
    );
  }

  if ((selectedWbs || selectedId) && isVisible) {
    let esriDom = document.querySelector('.esri-popup__main-container') as HTMLElement;
    if (esriDom) esriDom.style.display = 'none';
  }

  return (
    <>
      <div className={kls(styles.blockInfo)}>
        <div
          className="base-panel"
          style={
            (selectedWbs || selectedId) && isVisible
              ? { visibility: 'visible', marginBottom: 20 }
              : {
                  height: 0,
                  border: 0,
                  marginBottom: 0,
                  visibility: 'hidden',
                }
          }
        >
          <div className="base-panel-title" style={{ paddingLeft: 12, height: 48 }}>
            {/* 构件浮窗 */}
            <span className={styles.blockInfoTitle} title={processAccept?.wbsName || ''}>
              {processAccept?.wbsName}
            </span>
            <CloseOutlined
              style={{ float: 'right', margin: '14px 16px 0 0' }}
              className="custom-panel-title-close"
              // onClick={() => setIsVisible(false)}
              onClick={handleCloseClick}
            />
          </div>
          <div className="base-panel-body" style={{ padding: 16, minHeight: 240, height: 'unset' }}>
            <Tabs activeKey={curWorkingTab} onChange={setCurWorkingTab} size={'small'}>
              <TabPane
                {...TAB_CFG[0]}
                disabled={!selectedWbs}
                // className={kls(styles.blockInfoContent, styles.progress)}
              >
                {renderPoiPopup()}
              </TabPane>
              <TabPane
                {...TAB_CFG[1]}
                disabled={!selectedWbs}
                className={kls(styles.blockInfoContent, styles.progress)}
              >
                <p className={styles.code}>
                  {processAccept?.wbsName || TEXT_PLACE_HOLDER}{' '}
                  <span>{processAccept?.taskStatusDesc || TEXT_PLACE_HOLDER}</span>
                </p>
                <div className={kls('flex-spb', styles.info)}>
                  <div>{processAccept?.applyUserName || '--'}</div>

                  <p>{processAccept?.currentStepDesc || TEXT_PLACE_HOLDER}</p>
                </div>
                {renderBar(...(processAccept?.taskStatus?.split('/') || ''))}
                <div
                  className={styles.phone}
                  style={{
                    paddingTop: 24,
                  }}
                >
                  <div>负责人: {processAccept?.responsibleName || '--'}</div>
                </div>
                <div
                  className={styles.phone}
                  style={{
                    paddingTop: 6,
                  }}
                >
                  <PhoneOutlined /> 电话：{processAccept?.phone || '--'}
                </div>
              </TabPane>
              <TabPane
                {...TAB_CFG[2]}
                disabled={!selectedId || !qualityInspect}
                className={styles.blockInfoContent}
              >
                <div className={styles.list}>
                  {qualityInspect?.inspectDetailList?.map(
                    ({
                      applyLatitude = TEXT_PLACE_HOLDER,
                      applyLongitude = TEXT_PLACE_HOLDER,
                      handleLatitude = TEXT_PLACE_HOLDER,
                      handleLongitude = TEXT_PLACE_HOLDER,
                      inspectDesc = TEXT_PLACE_HOLDER,
                      phone = TEXT_PLACE_HOLDER,
                      responsibleName = TEXT_PLACE_HOLDER,
                      // linkUrl = '',
                    }) => {
                      return (
                        <div className={styles.qualityCard} key={responsibleName}>
                          <div className={styles.title}>
                            {responsibleName}
                            <a
                              href={
                                qualityInspect.linkUrl ? qualityInspect.linkUrl + searchStr : ''
                              }
                              target="_blank"
                            >
                              查看详情
                            </a>
                          </div>
                          <div className={styles.content}>{inspectDesc}</div>
                          <div className={styles.info}>
                            <div className={styles.location}>
                              <EnvironmentOutlined /> 位置（未关联wbs）
                            </div>
                            <div className={styles.call}>
                              <PhoneOutlined /> 电话：{phone}
                            </div>
                          </div>
                        </div>
                      );
                    },
                  )}
                </div>
              </TabPane>
              <TabPane
                {...TAB_CFG[3]}
                disabled={!selectedId || !safetyInspect}
                className={styles.blockInfoContent}
              >
                <div className={styles.list}>
                  {safetyInspect?.inspectDetailList?.map(
                    ({
                      applyLatitude = TEXT_PLACE_HOLDER,
                      applyLongitude = TEXT_PLACE_HOLDER,
                      handleLatitude = TEXT_PLACE_HOLDER,
                      handleLongitude = TEXT_PLACE_HOLDER,
                      inspectDesc = TEXT_PLACE_HOLDER,
                      phone = TEXT_PLACE_HOLDER,
                      responsibleName = TEXT_PLACE_HOLDER,
                      // linkUrl = '',
                    }) => {
                      return (
                        <div className={styles.qualityCard} key={responsibleName}>
                          <div className={styles.title}>
                            {responsibleName}
                            <a
                              href={safetyInspect.linkUrl ? safetyInspect.linkUrl + searchStr : ''}
                              target="_blank"
                            >
                              查看详情
                            </a>
                          </div>
                          <div className={styles.content}>{inspectDesc}</div>
                          <div className={styles.info}>
                            <div className={styles.location}>
                              <EnvironmentOutlined /> 位置（未关联wbs）
                            </div>
                            <div className={styles.call}>
                              <PhoneOutlined /> 电话：{phone}
                            </div>
                          </div>
                        </div>
                      );
                    },
                  )}
                </div>
              </TabPane>
            </Tabs>
          </div>
        </div>
      </div>
    </>
  );
}

export default BlockInfo;
